#!/bin/bash
# ----------------------------------------------------------------
#   4-RunBET.sh: Run the FSL Brain Extraction Tool
#	be used for un-warping later on
#
#	Usage:
#		3-B0_PrepareFieldmap.sh anatomyDirectory
#   initializes the Adaptation fMRI experiment. This experiment 
#   effect of stimulus history on the current evoked response,
#   on serial position -1 to -N are manipulated in a 
#
#
#   Inputs
#   -------
#   [protocolListFileName]: path to a file that should contain a
#   	description of the protocols to be used. If nothing is
#   	the file ./Config/ProtocolList.cfg will be used
#
#
#   Outputs
#   -------
#   ./Data/[expType]/[protocol]/[subjID]/[subjID]-[protocol]-
#  	this file will store all experimental info, experiment
#   	parameters, stimuli used, and data collected
#
#   Examples
#   -------
#    i) AdaptID_v1_1('./protocols.txt')
#   ii) AdaptID_v1_1
#
# ----------------------------------------------------------------
# ``Redistribution and use, with or without modification, are
#	permitted provided that the list of contributors below is
#	preserved.``
#
#   Original code by Marcelo G Mattar (09/04/2012)
#	mattar@sas.upenn.edu
# ----------------------------------------------------------------


# --- Check input command ---
if [ $# -ne 1 ]; then
cat << EOF
USAGE: `basename $0` anatomyDirectory
EOF
	exit 1
fi

# --- Read input parameters ---
anatomyDirectory=$1

# --- Keep a copy of calling directory, so that relative pathnames are properly used
OCD=$PWD


# --- Define some basic parameters ---
BET_THRESH=0.5
BETDIR=$anatomyDirectory/BET


# -----------------------------------------------------
# 1) --- CREATE BET DIRECTORY ---
# -----------------------------------------------------

# Create BET directory
if [ -d "$BETDIR" ]; then
	echo
	echo "WARNING: BET directory $BETDIR already exists!!!"
	read -p "Overwrite (y/n)? " -n 1
	if [[ ! $REPLY =~ ^[Yy]$ ]]
	then
		echo "Exiting..."
		echo
		exit 1
	fi
else
	echo
	mkdir $BETDIR
fi

echo


# -----------------------------------------------------
# 2) --- RUN BET ---
# -----------------------------------------------------

# Run BET at 3 different thresholds
for thisFile in $anatomyDirectory/*.nii*
do
	echo "Working on $thisFile"

	filename=`basename $thisFile`
	filename=`echo "$filename" | cut -d'.' -f1`

	/usr/local/fsl-5.0.1-centos5_64/bin/bet $thisFile $BETDIR/${filename}_brain_0.3 -R -f 0.3 -g 0 -o -m
	/usr/local/fsl-5.0.1-centos5_64/bin/bet $thisFile $BETDIR/${filename}_brain_0.4 -R -f 0.4 -g 0 -o -m
	/usr/local/fsl-5.0.1-centos5_64/bin/bet $thisFile $BETDIR/${filename}_brain_0.5 -R -f 0.5 -g 0 -o -m
done


# -----------------------------------------------------
# 3) --- COPY BRAIN EXTRACTED FILES TO ANALYSIS DIRECTORY ---
# -----------------------------------------------------

# Copy Brain files 
#cp $BETDIR/*0.4.nii.gz $analysesDir



cd $OCD

exit 0

